package movee.resilience4j;

import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import io.github.resilience4j.retry.RetryRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeoutException;

/**
 *
 * @author movee
 */
@Slf4j
@Service
public class RetryExam {

    /**
     * Retry的基本使用
     * @throws Throwable t
     */
    public void test() throws Throwable{
        // retry的配置：默认，custom，从基本config衍生
        RetryConfig config = RetryConfig.custom()
                .maxAttempts(2)
                .waitDuration(Duration.ofMillis(1000))
                .retryExceptions(IOException.class, TimeoutException.class)
                .build();

        // 默认配置创建retry实例
        // Retry retry = Retry.ofDefaults("test");

        // 自定义配置创建retry实例
        Retry retry = Retry.of("test", config);

        RetryRegistry registry = RetryRegistry.of(config);
        registry.retry("test", config);

        // 直接装饰并执行
        /*
        retry.executeCheckedSupplier(() -> {
            log.warn("retryyyyyyy");
            throw new Exception("xxxx");
        });

         */

        // 先装饰然后执行
        Retry.decorateCheckedSupplier(retry, () -> {
            log.warn("retryyyyyyy");
            throw new Exception("xxxx");
        }).get();

    }

}
